package org.micro.rbac.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.micro.rbac.service.InitDataService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 用户初始化或回复数据
 * 谨慎使用!!!
 * 谨慎使用!!!
 * 谨慎使用!!!
 *
 * @author hongsir
 * @since 2024/6/12
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class InitDataServiceImpl implements InitDataService {
    private final DataSource dataSource;

    @Override
    public void initTable() {
        String sqlPath = "db/schema-h2-init.sql";
        ClassPathResource resource = new ClassPathResource(sqlPath);
        Connection conn = DataSourceUtils.getConnection(dataSource);
        EncodedResource er = new EncodedResource(resource, "utf-8");
        ScriptUtils.executeSqlScript(conn, er);
    }

    @Override
    public void initData() {
        String sqlPath = "db/data-h2-init.sql";
        ClassPathResource resource = new ClassPathResource(sqlPath);
        Connection conn = DataSourceUtils.getConnection(dataSource);
        EncodedResource er = new EncodedResource(resource, "utf-8");
        ScriptUtils.executeSqlScript(conn, er);
    }

}
